package util;

import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import com.alibaba.druid.pool.DruidDataSource;

import entity.User;

/**
 * @author 李飞�?
 * @serialData 2018-8-15
 * @see 德鲁伊连接数据源
 */
public class DruidUtil<T> {
	static DruidDataSource datasource;
	static {
		datasource = new DruidDataSource();
		datasource.setDriverClassName("com.mysql.jdbc.Driver");
		datasource.setUrl("jdbc:mysql://localhost:3306/easybuy");
		datasource.setUsername("root");
		datasource.setPassword("zyc");
	}

	// 获取连接资源
	public static QueryRunner getQueryRunner() {
		QueryRunner qr = new QueryRunner(datasource);
		return qr;
	}

	// 通用增删改
	public static int InsertOrDelOrUpdate(String sql, Object... obj) throws SQLException {
		QueryRunner qr = DruidUtil.getQueryRunner();
		int update = qr.update(sql, obj);
		return update;
	}

	// 查询多个数据
	@SuppressWarnings("rawtypes")
	public static List selectManyDatas(String sql, Class<?> clas, Object... obj) throws SQLException {
		QueryRunner qr = DruidUtil.getQueryRunner();
		List query = qr.query(sql, new BeanListHandler<>(clas), obj);
		return query;
	}

	// 查询一条数据
	public static Object getOneData(String sql, Class<?> clas, Object... obj) throws SQLException {
		QueryRunner qr = DruidUtil.getQueryRunner();
		Object query =  qr.query(sql, new BeanHandler<>(clas), obj);
		return query;
	}

	// 查询右上角一个数据
	public static Object getOne(String sql, Object... obj) throws SQLException {
		QueryRunner qr = DruidUtil.getQueryRunner();
		Object query = qr.query(sql, new ScalarHandler<>(), obj);
		return query;
	}

}
